<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'process:fd:pmProjectSegmentation:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #pmProjectSplitNatureList>
        <BasicTable
          @register="registerPmProjectSplitNatureTable"
          @row-click="handlePmProjectSplitNatureRowClick"
        />
        <!-- <a-button class="mt-2" @click="handlePmProjectSplitNatureAdd" v-auth="'process:fd:pmProjectSegmentation:edit'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
      </template>
    </BasicForm>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="Flow_PmProjectSegmentation"
        completeText="提交"
        :loading="loadingRef"
        :auth="'process:fd:pmProjectSegmentation:edit'"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
    <ListSelect
      ref="fdlsit"
      v-show="false"
      selectType="natureSelect"
      :checkbox="true"
      :params="queryParams"
      :selectList="listSelectRef"
      @select="handSelect"
    />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsProcessFdPmProjectSegmentationForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    PmProjectSegmentation,
    pmProjectSegmentationSave,
    pmProjectSegmentationForm,
  } from '/@/api/process/fd/pmProjectSegmentation';
  import { BpmButton } from '/@/components/Bpm';
  import { pmProjectinformationTreeData } from '/@/api/proj/info/pmProjectinformation';
  import { ListSelect } from '/@/components/ListSelect';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('process.fd.pmProjectSegmentation');
  const { showMessage } = useMessage();
  const record = ref<PmProjectSegmentation>({} as PmProjectSegmentation);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: t('分单'),
  }));

  let listSelectRef = ref([]);
  let queryParams = ref({});
  let fdlsit = ref<any>('');
  const loadingRef = ref(false);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('工程名称'),
      field: 'oldid',
      fieldLabel: 'projInfo.projectname',
      component: 'TreeSelect',
      componentProps: {
        api: pmProjectinformationTreeData,
        params: {},
        canSelectParent: false,
        allowClear: false,
        onChange: async (e) => {
          queryParams.value = {
            pcode: e,
          };
          let arr = await pmProjectSplitNatureTable.getDataSource();
          let arrNew = [...arr];
          arrNew.forEach(async (item, index) => {
            console.log(index);
            // console.log(item,'111');
            await pmProjectSplitNatureTable.deleteTableDataRecord(item);
            // console.log(item,'2222');
          });
        },
      },
      dynamicDisabled: true,
      itemProps: { validateTrigger: 'blur' },
      required: true,
    },
    {
      label: t('工程编码'),
      field: 'oldid',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,
      },
      required: true,
    },
    {
      label: t('来源ID'),
      field: 'sourceId',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,
      },
      show: false,
    },
    {
      label: t('分单类型'),
      field: 'fdType',
      component: 'Select',
      componentProps: {
        dictType: 'zf_fd_type',
        allowClear: false,
        disabled: true,
      },
      required: true,
    },
    {
      label: t('分单名称'),
      field: 'name',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('分单原因类型'),
      field: 'reasonid',
      component: 'Select',
      componentProps: {
        dictType: 'zf_fd_reason',
        allowClear: true,
      },
      dynamicDisabled: true,
      required: true,
    },

    {
      label: t('分单原因'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 255,
      },
      dynamicDisabled: true,
      required: true,
    },
    {
      label: t('新工程编号'),
      field: 'newpjno',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,
      },
    },

    {
      label: t('分单图片'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'ProjectSegmentation_image',
        uploadType: 'image',
      },
      dynamicDisabled: true,
      colProps: { lg: 24, md: 24 },
      rules: [
        { required: true },
        {
          validator(_rule, value) {
            return new Promise((resolve, reject) => {
              const len = !value || value['ProjectSegmentation_image__len'] || 0;
              if (len == 0) reject(t('请上传分单图片！'));
              else resolve();
            });
          },
        },
      ],
    },
    {
      label: t('分单水表'),
      field: 'pmProjectSplitNatureList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'pmProjectSplitNatureList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerPmProjectSplitNatureTable, pmProjectSplitNatureTable] = useTable({
    // actionColumn: {
    //   width: 60,
    //   actions: (record: Recordable) => [
    //     {
    //       icon: 'ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handlePmProjectSplitNatureDelete.bind(this, record),
    //       },
    //       auth: 'process:fd:pmProjectSegmentation:edit',
    //     },
    //   ],
    // },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setPmProjectSplitNatureTableData(_res: Recordable) {
    pmProjectSplitNatureTable.setColumns([
      {
        title: t('extId'),
        dataIndex: 'extId',
        width: 130,
        align: 'left',
        ifShow: false,
      },
      {
        title: t('oldQty'),
        dataIndex: 'oldQty',
        width: 130,
        align: 'left',
        ifShow: false,
      },
      {
        title: t('水表编号'),
        dataIndex: 'metercode',
        width: 130,
        align: 'left',
      },
      {
        title: t('水表名称'),
        dataIndex: 'metername',
        width: 130,
        align: 'left',
      },

      {
        title: t('性质编码'),
        dataIndex: 'naturecode',
        width: 130,
        align: 'left',
      },
      {
        title: t('性质名称'),
        dataIndex: 'naturename',
        width: 130,
        align: 'left',
      },
      {
        title: t('水表口径'),
        dataIndex: 'caliber',
        width: 130,
        align: 'left',
      },
      {
        title: t('水表ID'),
        dataIndex: 'parentnatureid',
        width: 130,
        align: 'left',
      },

      {
        title: t('加压等级编号'),
        dataIndex: 'pressuregradecode',
        width: 130,
        align: 'left',
      },
      {
        title: t('加压等级名称'),
        dataIndex: 'pressuregradename',
        width: 130,
        align: 'left',
      },
      {
        title: t('DM分区'),
        dataIndex: 'dmapartition',
        width: 130,
        align: 'left',
      },

      {
        title: t('水表总数'),
        dataIndex: 'metercount',
        width: 130,
        align: 'center',
      },

      {
        title: t('最大数量'),
        dataIndex: 'nature.remaining',
        width: 130,
        align: 'center',
      },
      {
        title: t('本次拆分数'),
        dataIndex: 'splitedcount',
        width: 150,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 50,
        },
        editRule: true,
      },
    ]);
    pmProjectSplitNatureTable.setTableData(record.value.pmProjectSplitNatureList || []);
  }

  function handlePmProjectSplitNatureRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handlePmProjectSplitNatureAdd() {
    // pmProjectSplitNatureTable.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
    if (!getFieldsValue().oldid) {
      showMessage('请先选择工程名称！');
      return;
    }
    listSelectRef.value = [];
    fdlsit.value.handleInputClick();
  }

  async function handSelect(selectData) {
    let arr = await pmProjectSplitNatureTable.getDataSource();
    selectData.forEach((item) => {
      let flag = true;
      arr.forEach((res) => {
        if (res.parentnatureid == item.id) {
          flag = false;
        }
      });
      if (flag) {
        pmProjectSplitNatureTable.insertTableDataRecord({
          ...item,
          // id: new Date().getTime() + item.id,
          editable: true,
          isNewRecord: true,
          parentnatureid: item.id,
          nature: {
            remaining: item.remaining,
          },
          // munit: item.unit,
          // iqty: item.num,
        });
      }
    });
  }

  function handlePmProjectSplitNatureDelete(record: Recordable) {
    pmProjectSplitNatureTable.deleteTableDataRecord(record);
  }

  async function getPmProjectSplitNatureList() {
    let pmProjectSplitNatureListValid = true;
    let pmProjectSplitNatureList: Recordable[] = [];
    for (const record of pmProjectSplitNatureTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        pmProjectSplitNatureListValid = false;
      }
      pmProjectSplitNatureList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of pmProjectSplitNatureTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      pmProjectSplitNatureList.push({
        ...record,
        status: '1',
      });
    }
    if (!pmProjectSplitNatureListValid) {
      throw { errorFields: [{ name: ['pmProjectSplitNatureList'] }] };
    }
    return pmProjectSplitNatureList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmProjectSegmentationForm(data);
    record.value = (res.pmProjectSegmentation || {}) as PmProjectSegmentation;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setPmProjectSplitNatureTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      loadingRef.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.pmProjectSplitNatureList = await getPmProjectSplitNatureList();
      // console.log('submit', params, data, record);
      const res = await pmProjectSegmentationSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
